<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\User;
use App\Models\Product;
use App\Models\ProductVariant;
use App\Services\OrderNumberGenerator;

class OrderSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $users = User::all();
        $products = Product::with('variants')->get();

        if ($users->isEmpty() || $products->isEmpty()) {
            $this->command->info('需要先创建用户和产品数据');
            return;
        }

        // 创建5个订单
        for ($i = 0; $i < 5; $i++) {
            $user = $users->random();
            $orderDate = now()->subDays(rand(0, 7));
            
            $order = Order::create([
                'user_id' => $user->id,
                'order_number' => app(OrderNumberGenerator::class)->generate($orderDate),
                'status' => $this->getRandomStatus(),
                'payment_status' => $this->getRandomPaymentStatus(),
                'payment_method' => $this->getRandomPaymentMethod(),
                'total_amount' => 0,
                'subtotal_amount' => 0,
                'shipping_fee' => 10.00,
                'discount_amount' => 0,
                'receiver_name' => $user->name,
                'receiver_phone' => $user->phone ?? '13800138000',
                'receiver_address' => '广东省深圳市南山区科技园',
                'notes' => null,
                'created_at' => $orderDate,
                'updated_at' => $orderDate,
            ]);

            // 创建1-2个订单项
            $itemCount = rand(1, 2);
            $totalAmount = 0;

            for ($j = 0; $j < $itemCount; $j++) {
                $product = $products->random();
                
                // 根据商品类型处理变体
                if ($product->product_type === 'single') {
                    // 单规格商品，不使用变体
                    $variant = null;
                    $price = $product->price;
                    $sku = $product->sku;
                    $variantName = null;
                    $variantId = null;
                } else {
                    // 多规格商品，随机选择变体
                    if ($product->variants->isEmpty()) {
                        continue;
                    }
                    $variant = $product->variants->random();
                    $price = $variant->price;
                    $sku = $variant->sku;
                    $variantName = $variant->name;
                    $variantId = $variant->id;
                }
                
                $quantity = rand(1, 2);
                $subtotal = $price * $quantity;

                OrderItem::create([
                    'order_id' => $order->id,
                    'product_id' => $product->id,
                    'variant_id' => $variantId,
                    'sku' => $sku,
                    'product_name' => $product->name,
                    'variant_name' => $variantName,
                    'price' => $price,
                    'quantity' => $quantity,
                    'total_amount' => $subtotal,
                ]);

                $totalAmount += $subtotal;
            }

            // 更新订单总金额
            $order->update([
                'subtotal_amount' => $totalAmount,
                'total_amount' => $totalAmount + $order->shipping_fee - $order->discount_amount,
            ]);
        }

        $this->command->info('✅ 创建了 5 个订单');
    }

    private function getRandomStatus(): string
    {
        $statuses = ['pending', 'shipped', 'delivered'];
        return $statuses[array_rand($statuses)];
    }

    private function getRandomPaymentStatus(): string
    {
        $statuses = ['pending', 'paid'];
        return $statuses[array_rand($statuses)];
    }

    private function getRandomPaymentMethod(): string
    {
        $methods = ['alipay', 'wechat', 'cod'];
        return $methods[array_rand($methods)];
    }
}
